import json
import random

from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from rest_framework import status, serializers, mixins
from rest_framework.generics import ListAPIView, RetrieveAPIView, UpdateAPIView, CreateAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet

from answers.models import Label
from party.utils.qiniuyun.qiniu_storage import storage
from users.models import User
from users.serializers.modify import ModifyPersonInfomationViewSerializers, AddSkillLabelSerializers
from users.serializers.person import GetPersonInfoViewSerializers
from users.serializers.user import SMSCodeSerializers, UserSerizlizer, LoginViewSerializers, UserFansSerializer


class SMSCodeView(APIView):
    '''登录接口'''
    def get(self,request,mobile):
        '''get请求'''
        mobile = {"mobile":mobile}
        serializers = SMSCodeSerializers(data=mobile)
        serializers.is_valid(raise_exception=True)

        return Response(serializers.data)

class RegisterView(APIView):
    '''注册接口'''

    def post(self,request):
        '''post请求'''

        serializers = UserSerizlizer(data=request.data)

        serializers.is_valid(raise_exception=True)
        serializers.save()

        return Response(serializers.data,status=status.HTTP_201_CREATED)


class LoginView(APIView):
    '''登录接口'''

    def post(self,request):

        serializer = LoginViewSerializers(data = request.data)

        serializer.is_valid(raise_exception=True)

        return Response(serializer.data,status=status.HTTP_200_OK)


class GetPersonInfoView(APIView):
    '''获取个人信息类'''

    permission_classes = [IsAuthenticated]

    def get(self,request):

        user = User.objects.get(username=request.user)

        serizlizers = GetPersonInfoViewSerializers(user)

        return Response(serizlizers.data,status=status.HTTP_200_OK)

    def put(self,request):

        user = User.objects.get(id=request.user.id)
        request.data['username'] = request.user.username

        serializer = GetPersonInfoViewSerializers(user,data=request.data)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        return JsonResponse(serializer.data,status=status.HTTP_200_OK)


class ModifyPasswordPersonInfoView(APIView):
    '''修改密码接口'''
    permission_classes = [IsAuthenticated]

    def put(self,request):
        try:
            user = User.objects.get(username=request.user)
            password = request.data.get('password')
            user.set_password(password)
        except Exception:
            raise serializers.ValidationError('修改密码失败')
        return Response({"success":True,"message":"OK"},status=status.HTTP_200_OK)


class LikeUserInfoView(ModelViewSet):
    '''关注'''

    permission_classes = [IsAuthenticated]

    serializer_class = UserFansSerializer

    queryset = User.objects.all()

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('pk', False)
        instance = User.objects.get(id=request.user.id)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        instance.fans.add(User.objects.get(id=partial))
        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        return Response({"id":partial,"message":"ok","success":True},status=status.HTTP_200_OK)


    def destroy(self, request, *args, **kwargs):
        '''删除'''
        instance = self.get_object()

        user = User.objects.get(id=request.user.id)

        user.fans.remove(instance)


        return Response({"id":instance.id,"message":"ok","success":True},status=status.HTTP_204_NO_CONTENT)


class AddSkillsLabel(mixins.UpdateModelMixin,GenericViewSet):
    '''添加技能标签'''
    permission_classes = [IsAuthenticated]

    serializer_class = AddSkillLabelSerializers

    def get_object(self):

        return self.request.user

class AvatarView(APIView):
    '''upload user image'''
    def post(self,request):

        data = request.FILES.get('img')

        res = data.read()
        # 调用七牛云
        key = storage(res)
        # 保存文件
        url = 'http://qg5yaqh45.hd-bkt.clouddn.com/' + str(key)

        return Response({'imgurl':url})

class UploadAvatarView(APIView):
    '''upload image'''

    def post(self,request):

        data = request.FILES.get('img')

        res = data.read()
        # 调用七牛云
        key = storage(res)
        # 保存文件
        url = 'http://qg5yaqh45.hd-bkt.clouddn.com/' + str(key)

        return HttpResponseRedirect('http://scf-python.itheima.net/upload_success.html?image_url='+url)
